<template>
    <Frame>
        <template #header>
            课程：
        </template>
        <template #list>
            <List :questions="questions" :clicked="editQus" :current-question="form"></List>
        </template>
        <template #controllers>
            <span class="hint" style="margin-right: 20px;" > 语言环境:</span>
            <el-select  style="margin-right: 20px;" v-model="form2.language" class="m-2" placeholder="Select" size="default">
                <el-option
                v-for="item in lans"
                :key="item"
                :label="item"
                :value="item"
                />
            </el-select>
            <ElButton @click="newQus">创建题目</ElButton>
            <ElButton type="primary" @click="create">创建实验</ElButton>
        </template>
        <template #panel>
            <div v-if="mod !== 'none'">
                <ElForm :model="form" ref="formInstance" :rules="rules" :label-width="100">
                    <el-form-item label="问题描述" prop="description">
                        <el-input v-model="form.description" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }"/>
                    </el-form-item>
                    <el-form-item label="输入样例" prop="input">
                        <el-input v-model="form.input" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }"/>
                    </el-form-item>
                    <el-form-item label="输出样例" prop="output">
                        <el-input v-model="form.output" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }"/>
                    </el-form-item>
                    <el-form-item label="分值" prop="score">
                        <ElInputNumber v-model="form.score" :min="1"></ElInputNumber>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" v-if="mod === 'new'" plain @click="addQus">添加</el-button>
                        <el-button type="danger" v-if="mod === 'edit'" @click="deleteQ" plain>删除</el-button>
                        <el-button @click="clear" v-if="mod === 'new'">重置</el-button>
                        <el-button @click="save" v-if="mod === 'edit'">保存</el-button>
                    </el-form-item>
                </ElForm>
            </div>
            <div v-else>
                <div style="height: 200px;line-height: 200px;">请创建或选择修改题目</div>
            </div>
        </template>
    </Frame>

    <ElDialog 
        v-model="dialogVisiable"
        title="创建实验"
        width="30%"
        :show-close="false"
    >
        <ElForm ref="form2Instance" :model="form2" :rules="form2Rule" :label-width="100">
            <ElFormItem label="实验名称" prop="name" >
                <ElInput v-model="form2.name"></ElInput>
            </ElFormItem>
            <ElFormItem label="语言环境" prop="lan">
                <el-select v-model="form2.language" class="m-2" placeholder="Select" size="default">
                    <el-option
                    v-for="item in lans"
                    :key="item"
                    :label="item"
                    :value="item"
                    />
                </el-select>
            </ElFormItem>
            <el-form-item label="开始时间" prop="time">
                <el-date-picker
                    v-model="form2.startTime"
                    type="datetime"
                    placeholder="Select date and time"
                />
            </el-form-item>
            <el-form-item label="结束时间" prop="time">
                <el-date-picker
                    v-model="form2.endTime"
                    type="datetime"
                    placeholder="Select date and time"
                />
            </el-form-item>
        </ElForm>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisiable = false">取消</el-button>
                <el-button type="primary" @click="upload">
                Confirm
                </el-button>
            </span>
        </template>
    </ElDialog>
</template>

<script lang="ts" setup>
import { ref, onMounted, provide, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { FormInstance, FormRules } from 'element-plus';
import { useClientStore } from '../../pinia/stores/client';
import { storeToRefs } from 'pinia';

let loadingInstance: any
const route = useRoute()
const router = useRouter()
const courseId = route.params.courseId as string
const store = useClientStore()
const {currentCourseId,client} = storeToRefs(store)

const questions = ref(new Array<{
    description: string,
    input: string,
    output: string,
    score: number
}>())
const mod = ref<'new' | 'edit' | 'none'>('none')

const form = ref({
    description: '',
    input: '',
    output: '',
    score: 0,
    saved:false
})
const rules: FormRules = {
    description:{
        required:true,
        message:'请输入问题描述',
        trigger:'blur'
    },
    input:{
        // required:true,
        // message:'请输入输入样例',
        // trigger:'blur'
    },
    output:{
        required:true,
        message:'请输入输出样例',
        trigger:'blur'
    },
}
const formInstance = ref<FormInstance>()

const clear = () =>{
    form.value = {
        description: '',
        input: '',
        output: '',
        score: 0,
        saved:false
    }
}
const newQus = () =>{
    clear()
    mod.value = 'new'
}
const editQus = async (question:{
    description: string,
    input: string,
    output: string,
    score: number
}) =>{
    if(form.value.description === '' && form.value.input === '' && form.value.output === '' ){
        form.value = {
            ...question,
            saved:true
        }
        editingQuestion.value = question
        mod.value = 'edit'
        return
    }
    if(!form.value.saved){
        try {
            await ElMessageBox.confirm('是否保存当前题目？')
            await addQus()
            form.value = {
                ...question,
                saved:true
            }
        } catch (error) {
            console.log(error);
            if(error === 'cancel'){
                    form.value = {
                    ...question,
                    saved:true
                }
                
            }
        }
    }
    else{
        form.value = {
            ...question,
            saved:true
        }
    }
    editingQuestion.value = question
    mod.value = 'edit'
}
const deleteQ = () =>{
    questions.value.splice(questions.value.findIndex(q => q.description === form.value.description),1)
    clear()
}
const addQus = async () =>{
    try {
        if(questions.value.find(q => q.description === form.value.description)){
            ElMessage.warning('题目重复')
            return 
        }
        await formInstance.value!.validate()
        questions.value.push({
            description:form.value.description,
            input:form.value.input,
            output:form.value.output,
            score:form.value.score,
        })
        form.value.saved = true
        clear()
    } catch (error) {
        throw error
    }
}
const editingQuestion = ref<{
    description: string,
    input: string,
    output: string,
    score: number
}>()
const save = () =>{
    if(questions.value.findIndex(q => q.description === form.value.description)){
        ElMessage.warning('题目重复')
        return 
    }
    editingQuestion.value!.description = form.value.description
    editingQuestion.value!.input = form.value.input
    editingQuestion.value!.output = form.value.output
    editingQuestion.value!.score = form.value.score
    ElMessage.success('保存成功')
}

const form2 = ref({
    name:'',
    language:'不限' as '不限' | 'cpp'| 'rust'| 'python3'| 'go'| 'javascript'| 'java'| 'C#'|'php',
    startTime:new Date(),
    endTime:new Date(),
})
const form2Rule:FormRules = {
    name:{
        required:true,
        message:'请填写实验名称',
        trigger:'blur'
    },
    // lan:{
    //     required:true,
    //     message:'请选择语言环境',
    //     trigger:'blur'
    // }
}
const form2Instance = ref<FormInstance>()
const dialogVisiable = ref(false)
const lans = reactive(['不限','cpp', 'rust', 'python3', 'go', 'javascript', 'java', 'C#','php'])
const create = () =>{
    // const ret = await client.value.callApi('Experiment/CreateExp',{
    //     course:courseId
    // })
    dialogVisiable.value = true
}
const upload = async () =>{
    dialogVisiable.value = false
    loadingInstance = ElLoading.service({
        target:'#createTest'
    })
    try {
        await form2Instance.value!.validate()
        const ret = await client.value.callApi('Experiment/CreateExp',{
            course:courseId,
            ...form2.value,
            questions:questions.value
        })
        if(ret.isSucc){
            ElMessage.success('创建成功')
            router.back()
        }

    } catch (error) {
        console.log(error);
    }
    loadingInstance.close()
}

onMounted(() => {
    if(!courseId){
        ElMessage.error('不存在')
        return
    }
    else{
        currentCourseId.value = courseId
    }
    // loadingInstance = ElLoading.service({
    //     target:''
    // })
})
</script>

<style lang="less" scoped>
@fontColor: #a6a6a6;

.hint {
    color: @fontColor;
    font-size: 14px;
}

.item {
    // height: 40px;
    text-align: left;
    color: black;
    line-height: 40px;

    //   margin: 10px 0;
    .input {
        // padding: 0 20px;
        padding-left: 0%;
        width: 60%;
        margin-bottom: 10px;
    }

    .selection {
        // padding-left: 20px;
        height: 40px;
    }
}
</style>